package com.ybl.store.common.convention.result;

import com.ybl.store.common.convention.errorcode.BaseErrorCode;
import com.ybl.store.common.convention.exception.AbstractException;

import java.util.Optional;

/**
 * 全局返回对象构造器
 */
public final class Results {

    /**
     * 成功响应返回码
     */
    private static final String SUCCESS_CODE = "0";

    /**
     * 成功响应
     */
    public static Result<Void> success() {
        return new Result<Void>()
                .setCode(SUCCESS_CODE);
    }

    /**
     * 带响应数据的成功响应
     */
    public static <T> Result<T> success(T data) {
        return new Result<T>()
                .setCode(SUCCESS_CODE)
                .setData(data);
    }

    /**
     * 服务端失败响应
     */
    public static Result<Void> failure() {
        return new Result<Void>()
                .setCode(BaseErrorCode.SERVER_ERROR.code())
                .setMessage(BaseErrorCode.SERVER_ERROR.message());
    }

    /**
     * 通过 {@link AbstractException} 构建失败响应
     */
    public static Result<Void> failure(AbstractException exception) {
        return new Result<Void>()
                .setCode(Optional
                        .ofNullable(exception.code())
                        .orElse(BaseErrorCode.SERVER_ERROR.code()))
                .setMessage(Optional
                        .ofNullable(exception.message())
                        .orElse(BaseErrorCode.SERVER_ERROR.message()));
    }
}
